package main

import (
	"flag"
	"fmt"
	"github.com/google/uuid"
	"github.com/hashicorp/consul/api"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"net"
	_ "num_srv/initialization"
	"num_srv/internal/server"
	pb "num_srv/proto"
)

var (
	port = flag.Int("port", 50052, "The server port")
)

func main() {
	flag.Parse()
	ConsulRegister()
	s := grpc.NewServer()
	pb.RegisterNumServer(s, &server.Server{})
	lis, _ := net.Listen("tcp", fmt.Sprintf(":%v", *port))
	zap.S().Infof("server listening at %v", lis.Addr())
	if err := s.Serve(lis); err != nil {
		zap.S().Errorf("Failed server at %v", err.Error())
		return
	}
}

func ConsulRegister() {
	config := api.DefaultConfig()
	config.Address = fmt.Sprintf("http://%s:%d", "117.27.231.112", 8500)
	client, _ := api.NewClient(config)
	registration := &api.AgentServiceRegistration{
		ID:      uuid.NewString(),
		Name:    "num_srv",
		Port:    50052,
		Address: "127.0.0.1",
		Check: &api.AgentServiceCheck{
			HTTP:                           fmt.Sprintf("http://127.0.0.1:50052"),
			Interval:                       "10s",
			Timeout:                        "5s",
			DeregisterCriticalServiceAfter: "1m",
		},
	}
	err := client.Agent().ServiceRegister(registration)
	if err != nil {
		zap.S().Errorf("服务注册失败")
		return
	}
}
